<script setup lang="ts">
import NavBar from './components/NavBar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'

import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
// import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'
import { useGuessList } from '@/composables'

// 获取首页轮播图数据
const bannerList = ref<BannerItem[]>([])
const getBannerList = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}
// 获取首页分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategory = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}
// 获取首页热门推荐
const hotList = ref<HotItem[]>([])
const getHomeHot = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

// 显示骨架屏
const isLoading = ref(false)
// 要记得引入onLoad 从 @dcloudio/uni-app
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBannerList(), getHomeCategory(), getHomeHot()])
  isLoading.value = false
})
// 滚动触底刷新
// const guessRef = ref<XtxGuessInstance>()
// const onScrollBottom = () => {
//   guessRef.value?.getGuessLikeList()
// }
// 使用组合式函数完成 滚动触底刷新
const { onScrolltolower, guessRef } = useGuessList()

// 下拉刷新
// 刷新开关
const isTrigger = ref(false)
const onRefresh = async () => {
  isTrigger.value = true
  // 使用Promise.all() 等待所有请求完成
  await Promise.all([
    getBannerList(),
    getHomeCategory(),
    getHomeHot(),
    guessRef.value?.onRefreshReset(),
  ])
  isTrigger.value = false
}
</script>

<template>
  <!--导航栏-->
  <NavBar />
  <scroll-view
    :refresher-enabled="true"
    :refresher-triggered="isTrigger"
    :scroll-y="true"
    class="scroll-view"
    @refresherrefresh="onRefresh"
    @scrolltolower="onScrolltolower"
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!--轮播图-->
      <XtxSwiper :list="bannerList" />
      <!--分类-->
      <CategoryPanel :list="categoryList" />
      <!--热门推荐-->
      <HotPanel :list="hotList" />
      <!--猜你喜欢-->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss" scoped>
/* #ifdef APP-PLUS */
#app,
/* #endif */
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
